package com.yuneec.fly.views;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import com.yuneec.fly.R;

/**
 * Created by jw.gu on 2016/8/31 0031.
 */
public class DroneCompass extends View {
    private float droneAngle;
    private float cameraAngle;
    private Paint paint;
    private Bitmap droneBitmap;
    private Bitmap cameraBitmap;
    private Bitmap bgBitmap;
    private Rect bgRect;
    private boolean cameraShowable;

    public boolean isCameraShowable() {
        return cameraShowable;
    }

    public void setCameraShowable(boolean cameraShowable) {
        this.cameraShowable = cameraShowable;
    }

    public DroneCompass(Context context) {
        this(context, null);
    }

    public DroneCompass(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DroneCompass(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        cameraShowable = false;
        bgBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.bg_drone_compass);
        droneBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_drone_direction);
        cameraBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_camera_direction);
        paint = new Paint();
        paint.setAntiAlias(true);
    }

    public void setCameraAngle(float cameraAngle) {
        this.cameraAngle = cameraAngle;
        invalidate();
    }

    public void setDroneAngle(float droneAngle) {
        this.droneAngle = droneAngle;
        invalidate();
    }

    public void setDroneAndCameraAngle(float droneAngle, float cameraAngle) {
        this.droneAngle = droneAngle;
        this.cameraAngle = cameraAngle;
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (bgRect == null) {
            bgRect = new Rect();
            bgRect.left = 0;
            bgRect.top = 0;
            bgRect.right = getWidth();
            bgRect.bottom = getHeight();
        }
        canvas.drawBitmap(bgBitmap, null, bgRect, null);
        canvas.translate(getWidth() / 2, getHeight() / 2);
        if (cameraShowable) {
            canvas.save();
            canvas.rotate(cameraAngle);
            canvas.drawBitmap(cameraBitmap, -cameraBitmap.getWidth() / 2, -cameraBitmap.getHeight() / 2, paint);
            canvas.restore();
        }
        canvas.rotate(droneAngle);
        canvas.drawBitmap(droneBitmap, -droneBitmap.getWidth() / 2, -droneBitmap.getHeight() / 2, paint);
    }
}
